package com.mall.common.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.common.domain.content.ArticleCategoryDomain;
import com.mall.common.domain.content.TemplateDomain;
import com.mall.common.enums.TemplateType;
import com.mall.common.exception.NoticeException;
import com.mall.common.service.ArticleCategoryService;
import com.mall.common.service.TemplateService;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;

/**
 * 后台Action类 - 文章类别
 */
@Controller
@RequestMapping("/admin/system/articleCategory")
public class ArticleCategoryController extends BaseAuthController {
	@Resource private ArticleCategoryService articleCategoryService;
	@Resource private TemplateService templateService;
	
	/**
	 * 页面跳转
	 * @return 类别页面 article_category-main.ftl
	 * @author Administrator
	 */
	@RequestMapping(value="/main", method=RequestMethod.GET)
	public String main(Model model){
		return "/admin/system/articleCategory/main";
	}
	
	/**
	 * 页面跳转
	 * @return 类别页面 article_category-main.ftl
	 * @author Administrator
	 */
	@RequestMapping(value="/tree", method=RequestMethod.GET)
	public String tree(Model model){
		return "/admin/system/articleCategory/tree";
	}
	
	/**
	 * 文章分类树，用于文章管理页面
	 * 
	 * @author Administrator
	 */
	@RequestMapping(value="/tree/{style}", method=RequestMethod.GET)
	public String tree(@PathVariable String style, Model model){
		model.addAttribute("style", style);
		return "/admin/system/articleCategory/tree";
	}

	/**
	 * 
	 * @return 文章类别树
	 */
	@RequestMapping(value="/treeData", method=RequestMethod.POST)
	@ResponseBody
	public List<ArticleCategoryDomain> treeData(){
		ArticleCategoryDomain root = ArticleCategoryDomain.genRoot();
		List<ArticleCategoryDomain> categorys = articleCategoryService.getAll();
		categorys.add(root);
		return categorys;
	}

	/**
	 * 
	 * @return 文章类别树
	 */
	@RequestMapping(value="/treeData/{style}", method=RequestMethod.POST)
	@ResponseBody
	public List<ArticleCategoryDomain> treeData(@PathVariable String style){
		ArticleCategoryDomain root = ArticleCategoryDomain.genRoot();
		List<ArticleCategoryDomain> categorys = articleCategoryService.getAll();
		categorys.add(root);
		return categorys;
	}
	
	/**
	 * 转到新增和编辑页面
	 * @return 跳转到新增类别树页面
	 */
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String add(Long id, Model model){
		if(id != null){
			ArticleCategoryDomain article_category = articleCategoryService.find(id);
			if(article_category == null){
				throw new NoticeException("文章分类不存在");
			}
			model.addAttribute("article_category", article_category);
		}
		List<TemplateDomain> templates = templateService.getList("type", TemplateType.article);
		model.addAttribute("templateList", templates);
		buttonAuth("add", "/admin/system/articleCategory/save*", model);
		buttonAuth("update", "/admin/system/articleCategory/update*", model);
		buttonAuth("delete", "/admin/system/articleCategory/delete*", model);
		return "/admin/system/articleCategory/input";
	}
	
	/**
	 *  保存文章类别
	 * @return 跳转到新增类别树页面
	 */
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "name", message = "类别名称不能为空!")
		}
	)
	@RequestMapping(value="/save", method=RequestMethod.POST)
	public String save(ArticleCategoryDomain category, HttpServletResponse response){
		if(category.getCode().contains(".")){
			ArticleCategoryDomain upCategory = articleCategoryService.get("code", StringUtils.substringBeforeLast(category.getCode(), "."));
			if(upCategory != null){
				category.setParent(upCategory);
			}
		}
		if (!articleCategoryService.isUnique("code", null, category.getCode())){
			throw new NoticeException("error.unique", new Object[]{"分类编号"});
		}
		if(StringUtils.isNotBlank(category.getMark())
				&& !articleCategoryService.isUnique("mark", null, category.getMark())){
			throw new NoticeException("error.unique", new Object[]{"分类标识"});
		}
		articleCategoryService.persist(category);
		return ResponseUtils.renderJSON(category, response);
	}
	
	/**
	 *  删除文章类别
	 * @return 跳转到新增类别树页面
	 */
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "ids", message = "文章分类不存在")	
		}
	)
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(Long[] ids, HttpServletResponse response){
		articleCategoryService.remove(ids);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "id", message = "文章分类不存在")	
		},
		requiredStrings = {
			@RequiredStringValidator(fieldName = "name", message = "类别名称不能为空!")
		}
	)
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(ArticleCategoryDomain category, HttpServletResponse response){
		ArticleCategoryDomain current = articleCategoryService.find(category.getId());
		if(current == null){
			throw new NoticeException("文章分类不存在");
		}
		if(category.getCode().contains(".")){
			ArticleCategoryDomain upCategory = articleCategoryService.get("code", StringUtils.substringBeforeLast(category.getCode(), "."));
			category.setParent(upCategory);
		}
		if(!articleCategoryService.isUnique("code", current.getCode(), category.getCode())){
			throw new NoticeException("error.unique", new Object[]{"分类编号"});
		}
		if(StringUtils.isNotBlank(category.getMark())
				&& !articleCategoryService.isUnique("mark", category.getMark(), category.getMark())){
			throw new NoticeException("error.unique", new Object[]{"分类标识"});
		}
		articleCategoryService.update(category);
		return ResponseUtils.renderJSON(category, response);
	}
	
	@RequestMapping(value="/checkCode", method=RequestMethod.POST)
	public String checkCode(String oldValue, String code, HttpServletResponse response){
		if (articleCategoryService.isUnique("code", oldValue, code)) {
			return ResponseUtils.renderJSON("true", response);
		} else {
			return ResponseUtils.renderJSON("false", response);
		}
	}
	
	@RequestMapping(value="/checkMark", method=RequestMethod.POST)
	public String checkMark(String oldValue, String mark, HttpServletResponse response){
		if (articleCategoryService.isUnique("mark", oldValue, mark)) {
			return ResponseUtils.renderJSON("true", response);
		} else {
			return ResponseUtils.renderJSON("false", response);
		}
	}
	
}
